package org.zookeeper.examples.command.overview.component;

import java.io.IOException;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * 维护与zookeeper连接
 *
 * @author slydm
 */
public class Executor implements Watcher, Runnable, DataMonitor.MonitorLinstener {

  private String hostPort;
  private String znode;
  private final ZooKeeper zooKeeper;
  private final DataMonitor dataMonitor;

  public Executor(String hostPort, String znode) throws IOException {
    this.hostPort = hostPort;
    this.znode = znode;
    this.zooKeeper = new ZooKeeper(hostPort, 3000, this);
    this.dataMonitor = new DataMonitor(zooKeeper, znode, this);
  }

  @Override
  public void run() {
    try {
      synchronized (this) {
        while (!dataMonitor.isDead()) {
          wait();
        }
      }

      zooKeeper.close();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  /**
   * 被监视节点发生变化时的回调
   *
   * @param event
   */
  @Override
  public void process(WatchedEvent event) {

    System.out.println("Executor : 监视到节点发生变化...." + event);
    dataMonitor.process(event);

  }

  @Override
  public void exists(byte[] data) {
    String ch = new String(data);
    System.out.println("Executor收到变化后的数据 : " + ch);
    if ("886".equals(ch)) {
      this.shutdown();
    }
  }

  @Override
  public void close(int rc) {
    synchronized (this) {
      notifyAll();
    }
  }

  public void shutdown() {
    dataMonitor.setDead(true);
    this.close(Code.SESSIONMOVED.intValue());
  }
}
